package com.itheima.filter;

import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.FrameworkServlet;
import redis.clients.jedis.JedisPool;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFilter implements Filter {

    private ApplicationContext ac;

    private JedisPool jedisPool;

    private ServletContext servletContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        servletContext = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //从上下文域中取得ApplicationContext对象
        ac = (ApplicationContext) servletContext.getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "springmvc");

        //向下转型
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取请求对象中的访问url
        String url = req.getRequestURL().toString();

        //如果访问的资源在pages_login目录下则进行是否已登陆的校验
        if (url.contains("/pages_login")) {
            //从spring容器中获取JedisPool对象
            jedisPool = ac.getBean(JedisPool.class);
            //获取cookie中的手机号
            Cookie[] cookies = req.getCookies();

            if (cookies != null) {
                //遍历cookies
                for (Cookie cookie : cookies) {
                    String cookieName = cookie.getName();
                    //查询cookie名为login_member_telephone的值
                    if ("login_member_telephone".equals(cookieName)) {
                        //获取到cookie中的值，即登陆者的手机号
                        String telephone = cookie.getValue();
                        //从redis查询此手机号
                        String redisMember = jedisPool.getResource().get(telephone);
                        //如果查询到数据则放行
                        if (redisMember != null && redisMember.length() > 0) {
                            //放行
                            filterChain.doFilter(req, resp);
                            return;
                        }
                    }
                }
            }
            //如果没有查询到登陆信息则重定向至登陆页面
            resp.sendRedirect(req.getContextPath() + "/pages/login.html");
            return;
        }

        //放行
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
